package com.wsllx.controller;

import com.alibaba.fastjson2.JSONObject;
import com.wsllx.entity.Sms;
import com.wsllx.mapper.SmsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author liulx
 * @date 2022-08-30
 * @description 模拟其他系统回复
 */
@Slf4j
@RestController
@RequestMapping(value = "/sms")
public class SmsController {

    @Autowired
    private SmsMapper smsMapper;

    /**
     * 获取最新消息
     *
     * @return
     */
    @GetMapping("get")
    public List<Sms> get() {
        List<Sms> list = smsMapper.getByTime();
        return list;
    }

    /**
     * 添加短信数据到数据库
     *
     * @param json
     * @return
     * @throws Exception
     */
    @PostMapping("/add")
    public String add(@RequestBody String json) throws Exception {
        Sms model = JSONObject.parseObject(json, Sms.class);
        System.out.println(model);
        String phone = null;
        String content = null;
        if (model.getVal() != null) {
            String[] strings = model.getVal().split("\n");
            phone = strings[0];
            content = strings[1];
        }
        if (phone != null) {
            //发送过来的信息应该包含接收消息的手机号
            model.setKey(phone);
            model.setVal(content);
        }else {
            model.setKey("其他");
        }
        model.setStatus("E");
        model.setCreatedtime(new Date());
        int count = smsMapper.insert(model);

        if (count > 0) {
            return "添加成功";
        } else {
            return "添加失败";
        }
    }

}
